package com.fh.fruit.controller.periodTime;

import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.fh.controller.base.BaseController;
import com.fh.entity.Page;
import com.fh.entity.system.User;
import com.fh.fruit.entity.goods.Goods;
import com.fh.fruit.entity.goods.GoodsUnit;
import com.fh.fruit.entity.period.Period;
import com.fh.fruit.service.goods.GoodsManager;
import com.fh.fruit.service.period.PeriodManager;
import com.fh.util.Const;
import com.fh.util.DateUtil;
import com.fh.util.Jurisdiction;
import com.fh.util.PageData;

@Controller
@RequestMapping(value = "/period")
public class PeriodTimeController extends BaseController {
	String menuUrl = "period/listAllClassify.do"; // 商品地址(权限用)

	@Resource(name = "periodService")
	private PeriodManager periodService;

	@Resource(name = "goodsService")
	private GoodsManager goodsService;

	/**
	 * 显示分期列表
	 * 
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/list")
	public ModelAndView listGoods(Page page, HttpSession httpSession) throws Exception {
		ModelAndView mv = this.getModelAndView();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = new Date();
		PageData pd = this.getPageData();
		page.setPd(pd);
		List<GoodsUnit> unit = goodsService.getGoodsUnitList();
		List<Map<String, Object>> pt = periodService.getPeriodTimeList(page);
		User user = (User) Jurisdiction.getSession().getAttribute(Const.SESSION_USER);
		for (Map<String, Object> map : pt) {
			String end = (String) map.get("end_time");
			if (end != null) {
				Date et = sdf.parse(end);
				Date nt = sdf.parse(sdf.format(date));
				if (et.getTime() <= nt.getTime()) {
					map.put("updateId", user.getUSER_ID());
					map.put("updateTime", DateUtil.getTime());
					periodService.updateGoodsTimeState(map);
				}
			}
		}
		List<Map<String, Object>> baseList = periodService.getBaseList();
		mv.addObject("periodList", pt);
		mv.addObject("unit", unit);
		mv.addObject("pd", pd);
		mv.addObject("baseList", baseList);
		mv.setViewName("farm/period/period_list");
		mv.addObject("QX", Jurisdiction.getHC()); // 按钮权限
		return mv;
	}

	/**
	 * 显示基地列表ztree(分类管理)
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/listAllClassify")
	public ModelAndView listAllClassify(Model model, String id) throws Exception {
		ModelAndView mv = this.getModelAndView();
		try {
			mv.setViewName("farm/period/classify_ztree");
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
		return mv;
	}

	/**
	 * 异步加载树节点
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping("/asynTree")
	public void asynTree(HttpServletRequest request, HttpServletResponse response) throws Exception {
		PrintWriter out = null;
		response.setCharacterEncoding("UTF-8");
		logBefore(logger, "加载种植基地");
		String id = request.getParameter("id");
		String level = request.getParameter("level");
		List<PageData> lists = new ArrayList<>();
		List<Map<String, Object>> list = null;
		try {
			out = response.getWriter();
			if ("0".equals(id) && StringUtils.isEmpty(level)) {
				// 获取基地信息
				list = periodService.getBaseList();
			} else {
				list = new ArrayList<Map<String, Object>>();
			}
			for (int i = 0; i < list.size(); i++) {
				Map<String, Object> maps = list.get(i);
				PageData pd = new PageData();
				pd.put("id", maps.get("id"));
				pd.put("name", maps.get("name"));
				pd.put("isParent", true);
				pd.put("open", false);
				if ("0".equals(id) && StringUtils.isEmpty(level)) {
					pd.put("pId", "0");
					pd.put("pName", "");
					pd.put("url", "period/list.do?base_id=" + maps.get("id") + "&baseName=" + maps.get("name"));
				}
				pd.put("target", "treeFrame");
				lists.add(i, pd);
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
		logAfter(logger);
		out.write(JSON.toJSONString(lists));
	}

	/**
	 * 去新增商品页面
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/goAddG")
	public ModelAndView goAddG(Page page) throws Exception {
		if (!Jurisdiction.buttonJurisdiction(menuUrl, "add")) {
			return null;
		} // 校验权限
		ModelAndView mv = this.getModelAndView();
		// PageData pd = this.getPageData();
		List<Map<String, Object>> baseList = periodService.getBaseList();
		mv.setViewName("farm/period/period_edit");
		mv.addObject("msg", "saveG");
		mv.addObject("baseList", baseList);
		mv.addObject("QX", Jurisdiction.getHC()); // 按钮权限
		return mv;
	}

	/**
	 * 去选择商品页面
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "selectGoodsList")
	public ModelAndView selectGoodsList(Page page, HttpSession httpSession) throws Exception {
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		String keywords = pd.getString("keywords"); // 关键词检索条件
		if (StringUtils.isNotEmpty(keywords)) {
			pd.put("keywords", keywords.trim());
		}
		List<String> goodsId = periodService.getGoodsTimeGoodsNum(pd);
		pd.put("period", "period");
		if (!goodsId.isEmpty()) {
			pd.put("goodsId", goodsId);
		}
		page.setPd(pd);
		page.setShowCount(6);
		List<Goods> goodsList = goodsService.listGoods(page); // 列出商品列表
		mv.setViewName("farm/period/selectGoodsList");
		mv.addObject("goodsList", goodsList);
		mv.addObject("pd", pd);
		mv.addObject("QX", Jurisdiction.getHC()); // 按钮权限
		return mv;

	}

	/**
	 * 新增商品期次
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/saveGoodsTime")
	@ResponseBody
	public String saveGoodsTime(HttpServletRequest requset) throws Exception {
		if (!Jurisdiction.buttonJurisdiction(menuUrl, "add")) {
			return null;
		} // 校验权限
		logBefore(logger, Jurisdiction.getUsername() + "新增商品期次");
		String timeId = null;
		try {
			PageData pd = this.getPageData();
			int num = periodService.getGoodsTimeNum(pd);
			if (num != 0) {
				return "exist";
			}
			User user = (User) Jurisdiction.getSession().getAttribute(Const.SESSION_USER);
			pd.put("createId", user.getUSER_ID()); // 创建人
			pd.put("createTime", DateUtil.getTime()); // 创建时间
			timeId = periodService.saveGoodsTime(pd);
		} catch (Exception e) {
			e.printStackTrace();
			return "error";
		}
		return "success" + timeId;
	}

	/**
	 * 去修改商品期次页面
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/goodsGoodsTime")
	public ModelAndView goodsGoodsTime(Page page) throws Exception {
		if (!Jurisdiction.buttonJurisdiction(menuUrl, "edit")) {
			return null;
		} // 校验权限
		ModelAndView mv = this.getModelAndView();
		PageData pd = this.getPageData();
		Map<String, Object> goods = periodService.getGoodsByTimeId(pd);
		List<GoodsUnit> unit = goodsService.getGoodsUnitList();
		pd.put("goodsId", goods.get("id"));
		page.setPd(pd);
		List<Map<String, Object>> spec = periodService.getGoodsSpecTimeList(pd);
		mv.setViewName("farm/period/period_time_edit");
		mv.addObject("pd", pd);
		mv.addObject("goods", goods);
		mv.addObject("unit", unit);
		mv.addObject("goodsSpec", spec);
		mv.addObject("QX", Jurisdiction.getHC()); // 按钮权限
		return mv;
	}
	
	/**
	 * 修改时间
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/updateTime")
	public ModelAndView updateTime(Period period) throws Exception {
		if (!Jurisdiction.buttonJurisdiction(menuUrl, "edit")) {
			return null;
		} // 校验权限
		ModelAndView mv = this.getModelAndView();
		PageData pd = this.getPageData();
		List<Map<String, Object>> time = periodService.getHarvestTimeList(period);
		mv.setViewName("farm/period/period_harvest_time");
		mv.addObject("pd", pd);
		mv.addObject("time", time);
		mv.addObject("QX", Jurisdiction.getHC()); // 按钮权限
		return mv;
	}
	
	@RequestMapping(value = "updateHTime")
	public ModelAndView updateHTime(Period period) throws Exception {
		ModelAndView mv = this.getModelAndView();
		User user = (User) Jurisdiction.getSession().getAttribute(Const.SESSION_USER);
		period.setUpdateId(user.getUSER_ID());
		period.setUpdateTime(DateUtil.getTime());
		int num = periodService.updateHTime(period);
		if (num == 0) {
			mv.addObject("msg", "error");
		}
		mv.setViewName("save_result");
		mv.addObject("QX", Jurisdiction.getHC()); // 按钮权限
		return mv;

	}

	/**
	 * 去选择区域商品页面
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "bindingGoods")
	public ModelAndView bindingGoods(Page page, HttpSession httpSession) throws Exception {
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		/*
		 * List<String> countId=periodService.getGoodsTimeSpecCount(pd);
		 * if(!countId.isEmpty()){ pd.put("countId", countId); }
		 */
		page.setPd(pd);
		List<Map<String, Object>> areaGoods = periodService.getAreaGoodsList(page);
		mv.setViewName("farm/period/selectAreaGoods");
		mv.addObject("areaGoods", areaGoods);
		mv.addObject("pd", pd);
		mv.addObject("QX", Jurisdiction.getHC()); // 按钮权限
		return mv;

	}

	/**
	 * 商品规格期次新增
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "goodsSpecTime")
	public ModelAndView goodsSpecTime(Page page, HttpSession httpSession) throws Exception {
		ModelAndView mv = this.getModelAndView();
		PageData pd = this.getPageData();
		Map<String, Object> spec = goodsService.getGoodsSpecTime(pd);
		System.out.println(spec);
		String num = null;
		if (spec != null && !spec.isEmpty()) {
			if (spec.get("area_goods_count_id") != null) {
				pd.put("countId", (int) spec.get("area_goods_count_id"));
				num = periodService.getGoodsCount(pd);
			}
		}
		List<Map<String, Object>> harvest = periodService.getHarvestList(pd);
		mv.setViewName("farm/period/period_spec_edit");
		mv.addObject("pd", pd);
		mv.addObject("spec", spec);
		mv.addObject("harvestList", harvest);
		mv.addObject("num", num);
		mv.addObject("msg", "updateGoodsSpecTime");
		mv.addObject("QX", Jurisdiction.getHC()); // 按钮权限
		return mv;

	}

	@RequestMapping(value = "updateGoodsSpecTime")
	public ModelAndView saveGoodsSpecTime(Period period, HttpSession httpSession) throws Exception {
		ModelAndView mv = this.getModelAndView();
		User user = (User) Jurisdiction.getSession().getAttribute(Const.SESSION_USER);
		period.setUpdateId(user.getUSER_ID());
		period.setUpdateTime(DateUtil.getTime());
		int num = periodService.updateGoodsSpecTime(period);
		if (num == 0) {
			mv.addObject("msg", "error");
		} /*else if(num == 2){
			mv.addObject("msg", "批次已下单,参数未能修改");
		}*/
		mv.setViewName("save_result");
		mv.addObject("QX", Jurisdiction.getHC()); // 按钮权限
		return mv;

	}

	@RequestMapping(value = "goodsTime")
	@ResponseBody
	public String goodsTime(Page page, HttpSession httpSession) throws Exception {
		PageData pd = this.getPageData();
		try {
			User user = (User) Jurisdiction.getSession().getAttribute(Const.SESSION_USER);
			pd.put("updateId", user.getUSER_ID());
			pd.put("updateTime", DateUtil.getTime());
			int num = periodService.updateGoodsTimeNew(pd);
			if (num == 0) {
				return "error";
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "error";
		}

		return "success";
	}

	@RequestMapping(value = "checkCount")
	@ResponseBody
	public String checkCount(Page page, HttpSession httpSession) throws Exception {
		PageData pd = this.getPageData();
		try {
			int num = periodService.getGoodsSpecByCount(pd);
			if (num == 0) {
				return "error";
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "error";
		}

		return "success";
	}

	@RequestMapping(value = "updateSaleState")
	@ResponseBody
	public String updateSaleState(Page page, HttpSession httpSession) throws Exception {
		PageData pd = this.getPageData();
		try {
			User user = (User) Jurisdiction.getSession().getAttribute(Const.SESSION_USER);
			pd.put("updateId", user.getUSER_ID()); // 修改人
			pd.put("updateTime", DateUtil.getTime()); // 修改时间
			int num = periodService.updateSaleState(pd);
			if (num == 0) {
				return "failed";
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "failed";
		}

		return "success";
	}

	/**
	 * 保存商品
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "saveGoods")
	public ModelAndView saveGoods(HttpSession httpSession) throws Exception {
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		User user = (User) Jurisdiction.getSession().getAttribute(Const.SESSION_USER);
		pd.put("createId", user.getUSER_ID()); // 创建人
		pd.put("createTime", DateUtil.getTime()); // 创建时间
		periodService.saveGoods(pd);
		mv.setViewName("farm/period/selectAreaGoods");
		mv.addObject("pd", pd);
		mv.addObject("QX", Jurisdiction.getHC()); // 按钮权限
		return mv;

	}

	/**
	 * 修改期次信息
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/updateGoodsTime")
	public ModelAndView updateGoodsTime(Page page) throws Exception {
		if (!Jurisdiction.buttonJurisdiction(menuUrl, "edit")) {
			return null;
		} // 校验权限
		logBefore(logger, Jurisdiction.getUsername() + "修改期次");
		ModelAndView mv = this.getModelAndView();
		PageData pd = null;
		try {
			pd = this.getPageData();
			User user = (User) Jurisdiction.getSession().getAttribute(Const.SESSION_USER);
			pd.put("updateId", user.getUSER_ID()); // 修改人
			pd.put("updateTime", DateUtil.getTime()); // 修改时间
			int num = periodService.updateGoodsTime(pd);
			if (num == 0) {
				mv.addObject("msg", "failed");
			}
		} catch (Exception e) {
			logger.error(e.toString(), e);
			mv.addObject("msg", "failed");
		}
		mv.setViewName("save_result");
		return mv;
	}

	/**
	 * 去修改商品页面
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/goEditG")
	public ModelAndView goEditG(Page page) throws Exception {
		if (!Jurisdiction.buttonJurisdiction(menuUrl, "edit")) {
			return null;
		} // 校验权限
		ModelAndView mv = this.getModelAndView();
		PageData pd = this.getPageData();
		Map<String, Object> goodsTime = periodService.getGoodsTime(pd);
		List<GoodsUnit> unit = goodsService.getGoodsUnitList();
		mv.setViewName("farm/period/period_goods_time_edit");
		mv.addObject("pd", pd);
		mv.addObject("msg", "editG");
		mv.addObject("goods", goodsTime);
		mv.addObject("unit", unit);
		return mv;
	}

	/**
	 * 去绑定商品列表页面
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/toGoodsSpecTime")
	public ModelAndView toGoodsSpecTime(Page page) throws Exception {
		ModelAndView mv = this.getModelAndView();
		PageData pd = this.getPageData();
		page.setPd(pd);
		List<Map<String, Object>> specTime = periodService.getGoodsSpecTime(page);
		mv.setViewName("farm/period/goods_spec_time_list");
		mv.addObject("pd", pd);
		mv.addObject("specTime", specTime);
		mv.addObject("QX", Jurisdiction.getHC()); // 按钮权限
		return mv;
	}

	@RequestMapping(value = "/toGoodsSpecEdit")
	public ModelAndView toGoodsSpecEdit(Page page) throws Exception {
		ModelAndView mv = this.getModelAndView();
		PageData pd = this.getPageData();
		Map<String, Object> spec = goodsService.getGoodsSpecTime(pd);
		String num = null;
		if (spec != null && !spec.isEmpty()) {
			if (spec.get("area_goods_count_id") != null) {
				pd.put("countId", (int) spec.get("area_goods_count_id"));
				num = periodService.getGoodsCount(pd);
			}
		}
		if (spec != null) {
			int base_id = (int) spec.get("base_id");
			pd.put("base_id", base_id);
		}
		mv.setViewName("farm/period/period_goods_spec_edit");
		mv.addObject("pd", pd);
		mv.addObject("spec", spec);
		mv.addObject("num", num);
		mv.addObject("msg", "updateGoodsSpecTime");
		mv.addObject("QX", Jurisdiction.getHC()); // 按钮权限
		return mv;
	}

	/**
	 * 修改上下架状态
	 */
	@RequestMapping(value = "updateGoodsState")
	@ResponseBody
	public String updateGoodsState(Page page) throws Exception {
		if (!Jurisdiction.buttonJurisdiction(menuUrl, "update")) {
			return null;
		} // 校验权限
		PageData pd = this.getPageData();
		String msg = (String) pd.get("state");
		if ("01".equals(msg)) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date date = new Date();
			String endTime = pd.getString("endTime");
			Date et = sdf.parse(endTime);
			Date nt = sdf.parse(sdf.format(date));
			if (et.getTime() <= nt.getTime()) {
				return "timeEnd";
			}
			List<Map<String, Object>> spec = periodService.getGoodsSpecTimeList(pd);
			if (!spec.isEmpty()) {
				for (Map<String, Object> map : spec) {
					if (map.get("end_use_time") == null) {
						return "no-goods";
					}
					if (map.get("stock_num") == null) {
						return "no-goods";
					}
					if (map.get("price") == null) {
						return "no-goods";
					}
					String userTime = (String) map.get("end_use_time");
					Date e = sdf.parse(userTime);
					Date n = sdf.parse(sdf.format(date));
					if (e.getTime() <= n.getTime()) {
						return "userTimeEnd";
					}
					if (map.get("area_goods_count_id") != null) {
						pd.put("countId", (int) map.get("area_goods_count_id"));
						Map<String, Object> count = periodService.getAreaGoodsCount(pd);
						if (!count.isEmpty()) {
							int stock_num = (int) map.get("stock_num");
							int number = (int) count.get("num");
							int take_num = (int) count.get("take_num");
							if (stock_num > (number - take_num)) {
								return "no-stock";
							}
							String state = (String) count.get("state");
							if ("00".equals(state)) {
								return "no-state";
							}
						}
					} else {
						return "no-goods";
					}
				}
			} else {
				return "no-spec";
			}
		}
		User user = (User) Jurisdiction.getSession().getAttribute(Const.SESSION_USER);
		pd.put("updateId", user.getUSER_ID()); // 修改人
		pd.put("updateTime", DateUtil.getTime()); // 修改时间
		int number = periodService.updateGoodsState(pd);
		return number == 1 ? "success" : "failed";
	}

	@RequestMapping(value = "getGoodsCount")
	@ResponseBody
	public String getGoodsCount(Page page) throws Exception {
		if (!Jurisdiction.buttonJurisdiction(menuUrl, "update")) {
			return null;
		} // 校验权限
		PageData pd = this.getPageData();
		String num = periodService.getGoodsCount(pd);
		return num;
	}

	/**
	 * 批量修改上下架状态
	 */
	@RequestMapping(value = "updateBatchState")
	@ResponseBody
	public String updateBatchState(Page page) throws Exception {
		if (!Jurisdiction.buttonJurisdiction(menuUrl, "update")) {
			return null;
		} // 校验权限
		PageData pd = this.getPageData();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = new Date();
		User user = (User) Jurisdiction.getSession().getAttribute(Const.SESSION_USER);
		String stat = pd.getString("state");
		String ids = pd.getString("ids");
		String[] str = ids.split(",");
		int number = 0;
		for (String id : str) {
			PageData p = new PageData();
			p.put("timeId", id);
			p.put("updateTime", DateUtil.getTime());
			p.put("updateId", user.getUSER_ID());
			p.put("state", stat);
			if ("01".equals(stat)) {
				Map<String, Object> goodsTime = periodService.getGoodsTime(p);
				if (goodsTime != null) {
					String endTime = (String) goodsTime.get("end_time");
					Date et = sdf.parse(endTime);
					Date nt = sdf.parse(sdf.format(date));
					if (et.getTime() <= nt.getTime()) {
						return "timeEnd" + id;
					}
				} else {
					return "failed";
				}
				List<Map<String, Object>> spec = periodService.getGoodsSpecTimeList(p);
				if (!spec.isEmpty()) {
					for (Map<String, Object> map : spec) {
						p.put("specTimeId", map.get("id"));
						if (map.get("end_use_time") == null) {
							return "no-goods" + id;
						}
						if (map.get("stock_num") == null) {
							return "no-goods" + id;
						}
						if (map.get("price") == null) {
							return "no-goods" + id;
						}
						String userTime = (String) map.get("end_use_time");
						Date e = sdf.parse(userTime);
						Date n = sdf.parse(sdf.format(date));
						if (e.getTime() <= n.getTime()) {
							return "userTimeEnd" + id;
						}
						if (map.get("area_goods_count_id") != null) {
							p.put("countId", (int) map.get("area_goods_count_id"));
							Map<String, Object> count = periodService.getAreaGoodsCount(p);
							if (!count.isEmpty()) {
								int stock_num = (int) map.get("stock_num");
								number = (int) count.get("num");
								int take_num = (int) count.get("take_num");
								if (stock_num > (number - take_num)) {
									return "no-stock" + id;
								}
								String state = (String) count.get("state");
								if ("00".equals(state)) {
									return "no-state" + id;
								}
							}
						} else {
							return "no-goods" + id;
						}
						number = periodService.updateSpecTimeState(p);
					}
				} else {
					return "no-spec" + id;
				}

			}
			number = periodService.updateGoodsState(p);

		}
		return number == 1 ? "success" : "failed";
	}

}
